
#include "member_BSurface.h"

using namespace BWE;

member_BSurface::member_BSurface(BSurface* rectangle)
{
	boss = rectangle;
	rightSegment = 3;
	frontSegment = 3;
}
member_BSurface::~member_BSurface()
{

}

bool member_BSurface::rebuild()
{
	int count = (rightSegment + 1) * (frontSegment + 1);
	if (count == 0)
	{
		boss->clear();
		return true;
	}

	BVectorArray* vertices = boss->vertices();
	BVectorArray* normals = boss->normals();
	BCoordArray* coords = boss->texCoords();

	if (!vertices || vertices->size() != count)
	{
		vertices = new BVectorArray(count);
		normals = new BVectorArray(count);
		coords = new BCoordArray(count);
		boss->setVertices(vertices);
		boss->setNormals(normals);
		boss->setTexCoords(coords);
	}

	BVector normal = right.cross(front);
	normal.normalize();
	BVector svr = right / rightSegment;
	BVector svf = front / frontSegment;
	float tdx = 1.0f / rightSegment;
	float tdy = 1.0f / frontSegment;

	for (int r = 0; r < frontSegment + 1; r++)
	{
		int head = r * (rightSegment + 1);
		BVector vfront = svf * r;
		float ty = tdy * r;
		for (int c = 0; c < rightSegment + 1; c++)
		{
			int index = head + c;
			BVector vright = svr * c;
			(*vertices)[index] = origin + vright + vfront;
			(*normals)[index] = normal;
			(*coords)[index].set(tdx * c, ty);
		}
	}

	BIndexArray* indices = new BIndexArray(rightSegment * frontSegment * 4);
	BPrimitive* primitive = new BPrimitive(BPrimitive::Quads, indices);
	int fi = 0;
	for (int r = 0; r < frontSegment; r++)
	{
		int head = r * (rightSegment + 1);
		int pos = r * rightSegment * 4;
		for (int c = 0; c < rightSegment; c++)
		{
			int i0 = head + c;
			int i1 = i0 + 1;
			int i2 = i1 + (rightSegment + 1);
			int i3 = i0 + (rightSegment + 1);
			(*indices)[pos + c * 4] = i0;
			(*indices)[pos + c * 4 + 1] = i1;
			(*indices)[pos + c * 4 + 2] = i2;
			(*indices)[pos + c * 4 + 3] = i3;
		}
	}

	boss->addPrimitive(primitive);

	return true;
}
